package com.example.cliente;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;


import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.LinearLayout.LayoutParams;


public class cliente extends Activity {
//implements ActionBar.TabListener {


	public static SectionsPagerAdapter mSectionsPagerAdapter;
	public static ViewPager mViewPager;
 	public static plc_cliente miPlc;
	public static Context ctx;
	public static int pagina;
	public static Socket misocket; 
	public static ObjectOutputStream out ;	
	public static ObjectInputStream in ;
	public static int width;
	public static int height;
	public static String nombre_servidor;
	public static String pass_servidor;
	public static String dir_espejo;
	
	private static final int RESULT_SETTINGS = 1;

	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ctx = this;
        
		SharedPreferences sharedPref = PreferenceManager
				.getDefaultSharedPreferences(this);

      
		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		width = size.x;
		height = size.y;
        // Set up the action bar.
   //     final ActionBar actionBar = getActionBar();
    //    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
    //            actionBar.setSelectedNavigationItem(position);
            }
        });

		
			nombre_servidor = sharedPref.getString("NOMBRE_SERVIDOR", "");
			pass_servidor = sharedPref.getString("PASS_SERVIDOR", "");
			dir_espejo = sharedPref.getString("DIR_ESPEJO", "");
			
        	if (nombre_servidor.equals("")){
      			Intent i = new Intent(this, preferencias.class);
      			startActivityForResult(i, RESULT_SETTINGS);
        	}
        	else{
        		Log.e("smain", "lanzo el thread");

        		sock_cliente comunicacion = new sock_cliente ();
        		comunicacion.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        	}

		
		
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
		switch (item.getItemId()) {
		case R.id.menu_settings:		
		Intent i = new Intent(this, preferencias.class);
		startActivityForResult(i, RESULT_SETTINGS);
		return true;

		default:
			return super.onOptionsItemSelected(item);
		}
    }

 /*   @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }
*/
    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position);
        }

        @Override
        public int getCount() {
        	return servidor_cliente.plcs.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
			plc_cliente p = servidor_cliente.plcs.get(position);
			return p.nombre;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
   //         View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            
			plc_cliente mp = servidor_cliente.plcs.get(getArguments().getInt(ARG_SECTION_NUMBER));
			View rootView =  inflater.inflate(R.layout.comunicacion_item_detail,
					container, false);
			//if (servidor_cliente.nombre != null && servidor_cliente.nombre.length() != 0){	
		
			ScrollView miscroll = (ScrollView) rootView.findViewById(R.id.miscroll);
			miscroll.setScrollbarFadingEnabled(false);	
			miscroll.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);
			LinearLayout milayout = dibuja_cliente.rellena(mp);
			miscroll.addView(milayout);
	//	}
            return rootView;
        }
    }

}




/*
------------------------------------------------------------------------------------------------------------
package com.example.cliente;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

//import com.example.tabulado.plc;
//import com.example.tabulado.poner_password;
//import com.example.tabulado.servidor;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
//import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

public class cliente extends Activity {

	SectionsPagerAdapter mSectionsPagerAdapter;
//	public static SectionsPagerAdapter mSectionsPagerAdapter;
	public static ViewPager mViewPager;
 	public static plc_cliente miPlc;
	public static Context ctx;
	//public static int indvariable;
	//public static int indalarma;
	public static int pagina;
	public static ListView listaVariables;
	public static TextView texto ;
	public static Socket misocket; 
	public static ObjectOutputStream out ;	
	public static ObjectInputStream in ;
	boolean clickvariable =false;
	
	static ActionMode mActionMode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		ctx = this;		
		Log.e("smain", "arranco");
		mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		mViewPager.getCurrentItem();
		
		if  (servidor_cliente.nombre == null  ){
			poner_password_cliente dialogo_pass = new poner_password_cliente();	
		   	dialogo_pass.show(getFragmentManager(), "Conectar con servidor");
		}
	
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
//-------------------------------------------------------------------------------------------------------------		
//   creamos notificacion de alarmas--------------------------------------------------------------------------	
//-------------------------------------------------------------------------------------------------------------

	/*	Notification.Builder mBuilder =
		        new Notification.Builder(this)
		        .setSmallIcon(R.drawable.ic_launcher)
		        .setContentTitle("My notification")
		        .setContentText("Hello World!");	
		Intent resultIntent = new Intent(this, panelAlarmas_cliente.class);
		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(panelAlarmas_cliente.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(resultIntent);
		PendingIntent resultPendingIntent =stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		int mId = 1;
		NotificationManager mNotifyMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotifyMgr.notify (mId, mBuilder.build());
		
//--------------------------------------------------------------------------------------------------------------------		
		
		 
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

		getMenuInflater().inflate(R.menu.activity_main, menu);
		// MenuItem i = menu.findItem(R.id.menu_editar);
		// i.setIcon(R.drawable.ic_action_name);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {

		default:
			return super.onOptionsItemSelected(item);
		}
	}


	public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
		
		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {

			miPlc = servidor_cliente.plcs.get(position);

			Bundle args = new Bundle();
			Fragment fragment = new comunicacionFragment();
				args.putInt(comunicacionFragment.ARG_SECTION_NUMBER, position);
				fragment.setArguments(args);
			
			return fragment;
		}

		public int getItemPosition(Object item) {
			return POSITION_NONE;
		}

		@Override
		public int getCount() {
			return servidor_cliente.plcs.size();
		}

		@Override
		public CharSequence getPageTitle(int position) {
			plc_cliente p = servidor_cliente.plcs.get(position);
			return p.nombre;
		}
	}

	public class comunicacionFragment extends Fragment {

		public static final String ARG_SECTION_NUMBER = "section_number";
//		public  int plcId =getArguments().getInt(ARG_SECTION_NUMBER);
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			plc_cliente mp = servidor_cliente.plcs.get(getArguments().getInt(ARG_SECTION_NUMBER));
			View rootView =  inflater.inflate(R.layout.comunicacion_item_detail,
					container, false);
			if (servidor_cliente.nombre != null && servidor_cliente.nombre.length() != 0){	
			LinearLayout milayout =dibuja_cliente.rellena(mp);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
			lp.setMargins(30,0, 0, 0);
		
			milayout.setLayoutParams(lp);			
			 ((ViewGroup) rootView).addView(milayout);
		}

			return rootView;
		}
	}

	// ------------------------------------------------------------------------------------------------------
	// ------------------ MENU contextual
	// ----------------------------------------------------------------

	public   ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

		// Called when the action mode is created; startActionMode() was called
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			// Inflate a menu resource providing context menu items
			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate(R.menu.menu_variables, menu);
			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false; // Return false if nothing is done
		}

		// Called when the user selects a contextual menu item
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			
			switch (item.getItemId()) {
			default:
				return false;
			}
		}

		// Called when the user exits the action mode
		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mActionMode = null;
		}
	};
	

}
*/
